package com.darker.common.rabbit.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class RabbitService {
    @Lazy
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     *  发送消息
     * @param exchange 交换机
     * @param routingKey 路由键
     * @param message 消息
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
        return true;
    }
    public boolean sendMessageAndCorrelationData(String exchange, String routingKey, Object message) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        correlationData.getFuture().addCallback(
                result -> {
                    if (result.isAck()){
                        log.info("消息发送路由器成功,ID=>{}",correlationData.getId(),message);
                    }else{
                        log.info("消息发送到路由器失败,ID=>{},message=>{}",correlationData.getId(),message);
                        rabbitTemplate.convertAndSend(exchange, routingKey, message);
                    }
                }, ex -> {
                  log.error("消息发送异常, ID:{}, 原因{}",correlationData.getId(),ex.getMessage());
                }
        );
        rabbitTemplate.convertAndSend(exchange, routingKey, message,correlationData);
        return true;
    }


}

